<?php
/**
 * Created by PhpStorm.
 * User: Sojo
 * Date: 2017/5/31
 * Time: 17:36
 */
namespace App\Api\Service\Stock\Controllers;

use App\Eloquent\Ygt\CategoryFields;
use App\Eloquent\Ygt\Purchase;
use App\Eloquent\Ygt\PurchaseMaterial;
use App\Eloquent\Ygt\Qrcode;
use App\Eloquent\Ygt\StockFields;
use App\Eloquent\Ygt\UserMessage;
use Framework\BaseClass\Api\Controller;
use App\Eloquent\Ygt\StockIn;
use App\Eloquent\Ygt\StockOut;
use App\Eloquent\Ygt\Stock;
use App\Eloquent\Ygt\DepartmentUser;
use App\Eloquent\Ygt\Product;
use App\Engine\Stock as StockEngine;
use App\Engine\Func;
use App\Engine\Product as EngineProduct;
use App\Eloquent\Ygt\Message;
use App\Eloquent\Ygt\Privilege;
use App\Eloquent\Ygt\ProductFields;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class StockController extends Controller
{
    public $userId      = 25;

    public function getWaterList(){
        $userId             = Func::getHeaderValueByName( 'userid',$this->userId );
        $userInfo           = DepartmentUser::getCurrentInfo( $userId );
        $companyId          = $userInfo->company_id;
        if(!$userInfo)
        {
            xThrow(ERR_PARAMETER,'登录失败');
        }
        $date          = request('date','');
        $page          = request('page',1);


        //取材料的流水
        $limit          = 10;
        $offset         = ($page - 1) * $limit;

        $StockWaterObj = new Stock();
        if(!empty($date)){
            $startTime = strtotime($date);
            $endTime = $startTime+24*3600;

            $StockWaterObj = $StockWaterObj->whereBetween('ygt_stock.created_at',[$startTime,$endTime]);
        }
        //2019-01-23 Linwei  增加本厂限制
        $StockWaterObj->where("company_id","=",$companyId);
        //获得总数
        $count = $StockWaterObj->count();

        //获得数据
        $lists = $StockWaterObj->leftJoin('ygt_product','ygt_product.id','=','ygt_stock.product_id')
            ->leftJoin('ygt_user','ygt_user.id','=','ygt_stock.operate_uid')
            ->skip($offset)->take($limit)
            ->orderBy('created_at','desc')
            ->get([
                'ygt_stock.id',
                'ygt_stock.type',
                'ygt_stock.relate_type',
                'ygt_stock.number',
                'ygt_stock.last_product_number as residual_number',
                'ygt_stock.water_no as sn',
                'ygt_stock.created_at',
                'ygt_stock.place_name',
                'ygt_product.product_name as name',
                'ygt_product.seller_company_id',
                'ygt_product.customer_id',
                'ygt_product.assemblage_material_id',
                'ygt_user.truename as operate_name'
            ]);
        $lists      = StockEngine::composeList($lists)->toArray();
//        //修改时间显示格式
//        foreach ($lists as $key => $tmpRow){
//            $lists[$key]['created_at'] = date('Y-m-d H:i:s',$tmpRow['created_at']);
//        }

        $listData           = [
            'list'=>$lists,
        ];
        $pagingData         = [
            'page' => $page,
            'pageSize' => $limit,
            'total' => $count,
            'keyword' => ''
        ];
        return $this->pagingData($listData, $pagingData);
    }


    public function getProductInfo(){
        $userId             = Func::getHeaderValueByName( 'userid',$this->userId );
        $userInfo           = DepartmentUser::getCurrentInfo( $userId );
        if(!$userInfo)
        {
            xThrow(ERR_PARAMETER,'登录失败');
        }
        //额外信息
        $extra = [
            'is_warehouse_role'=>0
        ];
        $companyId          = $userInfo->company_id;
        $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 7);
        if (in_array($userInfo['privilege_id'], $privilegeIdList)) {
            $extra['is_warehouse_role'] =1;
        }

        $id          = request('id');

        //获取集合材料下第一个材料
        $materialId = $id;
        if(strstr($materialId,'A')){
            $tmpAssemblageMaterialId = str_replace('A','',$materialId);
            $materialRow = \App\Eloquent\Ygt\Product::where(['assemblage_material_id'=>$tmpAssemblageMaterialId])->first();
            if($materialRow){
                $id = $materialRow['id'];
            }
        }

        if (!$id)
        {
            xThrow(ERR_PARAMETER);
        }

        //获得商品基本信息
        $fileds = [
            'ygt_product.id',//id
            'ygt_product.product_name',//名称
            'ygt_product.product_no',//编号
            'ygt_product.number',//库存
            'ygt_product.warning_number',//预警数量
            'ygt_product.unit',//库存单位
            'ygt_product.place_name',//摊位
            'ygt_product.weight',//克重
            'ygt_product.spec',//规格
            'ygt_product.seller_company_id',//供应商id
            'ygt_product.customer_id',//客户id
            'ygt_product.measurement_attribute',//计量属性
            'ygt_product.assemblage_material_id',//集合材料ID
            'ygt_product.price',//单价
            'ygt_customer.customer_name',
            'ygt_seller_company.title as supplier_name',
            'ygt_product.img_id',//图片id
        ];
        $baseInfo = Product
            ::leftJoin('ygt_customer','ygt_customer.id','=','ygt_product.customer_id')
            ->leftJoin('ygt_seller_company','ygt_seller_company.id','=','ygt_product.seller_company_id')
            ->where('ygt_product.id','=',$id)->first($fileds);
        if($baseInfo){
           $baseInfo = $baseInfo->toArray();
           if(!$baseInfo['measurement_attribute']){//处理null
               $baseInfo['measurement_attribute'] = '';
           }
        }
        else{
            xThrow(ERR_PARAMETER);
        }

        if(!$baseInfo['customer_id']){
            $baseInfo['customer_name'] = '';
        }

        if(!$baseInfo['seller_company_id']){
            $baseInfo['supplier_name'] = '';
        }

        if($baseInfo['img_id']){
            $baseInfo['img_url'] = Func::getImgUrlById($baseInfo['img_id']);
        }
        else{
            $baseInfo['img_url'] = '';
        }

//        //获得最新一次的采购价格
//        $latestProcurementPriceInfo = $this->getLatestProcurementPriceInfo($id);
//        if($latestProcurementPriceInfo){
//
//            $baseInfo['price'] = sprintf("%.2f",$latestProcurementPriceInfo['total_price']/$latestProcurementPriceInfo['number']);
//            $baseInfo['total_price'] = $baseInfo['price']*($baseInfo['number']/$latestProcurementPriceInfo['number']);
//            $baseInfo['total_price'] = sprintf("%.2f",$baseInfo['total_price']);
//        }
//        else{
//            $baseInfo['price'] = '';
//            $baseInfo['total_price'] = '';
//        }

        //数据调整，单价直接取材料表的单价 20181112 zhuyujun
        $baseInfo['total_price'] = 0;
        if($baseInfo['price']){
            $baseInfo['total_price'] = $baseInfo['price']*$baseInfo['number'];
            $baseInfo['total_price'] = '¥'.sprintf("%.2f",$baseInfo['total_price']);
        }


        //平均损耗率
        $baseInfo['attrition_rate'] = '';

        //预警日期
        $baseInfo['warning_date'] = '';

        //获得材料规格
        $baseInfo['attr_list']= $this->getAttrList($baseInfo['assemblage_material_id']);

        //处理计量属性字段
        if(!empty($baseInfo['attr_list'])){
            foreach ($baseInfo['attr_list'] as $key => $value){
                if($value['is_compute']){
                    $tmpObj = \App\Eloquent\Ygt\ProductFieldsCompute::where(['type'=>1,'material_id'=>$id,'product_fields_id'=>$value['id']])->first();
                    if($tmpObj){
                        if($tmpObj['number']){
                            $baseInfo['attr_list'][$key]['varchar'] = $tmpObj['number'];
                        }
                    }
                }
            }
        }

        //是否有采购员权限
        $isPurchasingAgent = 0;
        $companyId = $userInfo['company_id'];
        $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 10);
        if (in_array($userInfo['privilege_id'], $privilegeIdList)) {
            $isPurchasingAgent = 1;
        }

        //如果已有采购记录则不允许再修改
//        $latestProcurementPriceInfo = $this->getLatestProcurementPriceInfo($id);
//        if($latestProcurementPriceInfo){
//            $isPurchasingAgent = 0;
//        }
        //获取采购记录表是否有这个材料的记录
        $tmpPurchaseMaterialRow = \App\Eloquent\Ygt\PurchaseMaterial::where(['material_id'=>$id])->first();
        if($tmpPurchaseMaterialRow){
            $isPurchasingAgent = 0;
        }


        $baseInfo['is_purchasing_agent']= $isPurchasingAgent;
        $baseInfo['extra'] = $extra;
        return $baseInfo;
    }

    private function getAttrList($product_id){
        $fileds = ['id','field_name','varchar','unit','is_compute'];

        return ProductFields::where('assemblage_material_id','=',$product_id)
            ->get($fileds)
            ->toArray();
    }

    private function getLatestProcurementPriceInfo($product_id){
        $info = Stock::where('product_id','=',$product_id)
                ->where('relate_type','=',3)
                ->orderBy('created_at','desc')
                ->first(['number','total_price']);

        if($info){
            return $info->toArray();
        }

        return [];
    }


    public function getProductWaterList(){
        $userId             = Func::getHeaderValueByName( 'userid',$this->userId );
        $userInfo           = DepartmentUser::getCurrentInfo( $userId );
        if(!$userInfo)
        {
            xThrow(ERR_PARAMETER,'登录失败');
        }
        $date          = request('date','');
        $id          = request('id');
        $page          = request('page',1);

        if (!$id)
        {
            xThrow(ERR_PARAMETER);
        }

        //取材料的流水
        $limit          = 10;
        $offset         = ($page - 1) * $limit;

        $StockWaterObj = new Stock();
        $StockWaterObj = $StockWaterObj->where('product_id','=',$id);

        if(!empty($date)){
            $startTime = strtotime($date);
            $endTime = $startTime+24*3600;

            $StockWaterObj = $StockWaterObj->whereBetween('ygt_stock.created_at',[$startTime,$endTime]);
        }

        //获得总数
        $count = $StockWaterObj->count();

        $info =[];

        //获得可用库存
        $info['number'] = $StockWaterObj->sum('number');
        //获得累计入库数量
        $StockWaterObjTemp = clone $StockWaterObj;
        $info['in_number'] = $StockWaterObjTemp->where('ygt_stock.number','>',0)->sum('number');
        //获得累计出库数量
        $StockWaterObjTemp = clone $StockWaterObj;
        $info['out_number'] = $StockWaterObjTemp->where('ygt_stock.number','<',0)->sum('number');
        $info['out_number'] = -$info['out_number'];
        //获得数据
        $lists = $StockWaterObj
            ->leftJoin('ygt_user','ygt_user.id','=','ygt_stock.operate_uid')
            ->skip($offset)->take($limit)
            ->orderBy('created_at','desc')
            ->get([
                'ygt_stock.id',
                'ygt_stock.type',
                'ygt_stock.number',
                'ygt_stock.total_price',
                'ygt_stock.last_product_number as residual_number',
                'ygt_stock.water_no as sn',
                'ygt_stock.created_at',
                'ygt_stock.relate_type',
                'ygt_stock.place_name',
                'ygt_user.truename as operate_name'
            ]);
        $lists      = StockEngine::composeList($lists)->toArray();

        $listData           = [
            'info'=>$info,
            'list'=>$lists,
        ];
        $pagingData         = [
            'page' => $page,
            'pageSize' => $limit,
            'total' => $count,
            'keyword' => ''
        ];
        return $this->pagingData($listData, $pagingData);
    }

    public function getProductPurchaseWaterList(){
        $userId             = Func::getHeaderValueByName( 'userid',$this->userId );
        $userInfo           = DepartmentUser::getCurrentInfo( $userId );
        if(!$userInfo)
        {
            xThrow(ERR_PARAMETER,'登录失败');
        }

        //额外信息
        $extra = [
            'is_warehouse_role'=>0
        ];
        $companyId          = $userInfo->company_id;
        $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 7);
        if (in_array($userInfo['privilege_id'], $privilegeIdList)) {
            $extra['is_warehouse_role'] =1;
        }

        $date          = request('date','');
        $id          = request('id');
        $page          = request('page',1);

        if (!$id)
        {
            xThrow(ERR_PARAMETER);
        }

        //取材料的流水
        $limit          = 10;
        $offset         = ($page - 1) * $limit;

        $obj = new PurchaseMaterial();
        $obj = $obj->where('ygt_purchase_material.material_id','=',$id)
            ->leftJoin('ygt_purchase','ygt_purchase_material.purchase_id','=','ygt_purchase.id')
            ->where('ygt_purchase.status','=',1);

        if(!empty($date)){
            $startTime = strtotime($date);
            $endTime = $startTime+24*3600;

            $obj = $obj->whereBetween('ygt_purchase_material.created_at',[$startTime,$endTime]);
        }

        //获得总数
        $count = $obj->count();

        $info =[];
        //获得采购总量
        $info['number'] = $obj->sum('num');
        //获得采购总金额
        $info['money'] = $obj->sum(DB::raw('price*num'));
        //保留两位小数,添加货比符号
        $info['money'] = "¥".sprintf('%.2f',$info['money']);


        $lists = $obj
            ->leftJoin('ygt_user','ygt_user.id','=','ygt_purchase.uid')
            ->skip($offset)->take($limit)
            ->orderBy('ygt_purchase_material.created_at','desc')
            ->get([
                'ygt_purchase_material.id',
                //'ygt_stock.type',
                'ygt_purchase_material.num as number',
                'ygt_purchase_material.price',
                //'ygt_stock.last_product_number as residual_number',
                'ygt_purchase.purchase_number as sn',
                'ygt_purchase_material.created_at',
                //'ygt_stock.relate_type',
                'ygt_user.truename as operate_name'
            ])->toArray();

        foreach($lists as $key=>$val){
            $lists[$key]['created_time'] = date('Y-m-d H:i:s',$lists[$key]['created_at']);
            //$lists[$key]['price'] = sprintf("%.2f",$lists[$key]['total_price']/$lists[$key]['number']);
        }

        $listData           = [
            'info'=>$info,
            'list'=>$lists,
            'extra' => $extra
        ];
        $pagingData         = [
            'page' => $page,
            'pageSize' => $limit,
            'total' => $count,
            'keyword' => '',
        ];
        return $this->pagingData($listData, $pagingData);
    }

    //获得材料打码列表
    public function getProductQrCodeLog(){
        $userId             = Func::getHeaderValueByName( 'userid',$this->userId );
        $userInfo           = DepartmentUser::getCurrentInfo( $userId );
        if(!$userInfo)
        {
            xThrow(ERR_PARAMETER,'登录失败');
        }

        //获取产品id
        $product_id          = request('id');
        if (!$product_id)
        {
            xThrow(ERR_PARAMETER);
        }

        $page          = request('page',1);
        //取材料的流水
        $limit          = 10;
        $offset         = ($page - 1) * $limit;

        $obj = Qrcode::where('ygt_qrcode.product_id','=',$product_id);
        $count = $obj->count();

        $lists = $obj
            ->leftJoin('ygt_product','ygt_product.id','=','ygt_qrcode.product_id')
            ->skip($offset)->take($limit)->orderBy('id','desc')
            ->get([
                'ygt_qrcode.id',
                'ygt_qrcode.sn',
                'ygt_qrcode.product_id',
                'ygt_qrcode.total_number',
                'ygt_qrcode.now_number',
                'ygt_qrcode.stock_id',
                'ygt_qrcode.place_name',
                'ygt_product.product_name',
                'ygt_product.product_no',
            ])->toArray();

        $listData = [];
        foreach($lists as $key=>$val){
            $temp = $this->getProductQrCodeData($val);
            $listData[] = [
                'id'=>$val['id'],
                'product_name'=>$val['product_name'],
                'product_no'=>$val['product_no'],
                'total_number'=>$val['total_number'],
                'now_number'=>$val['now_number'],
                'place_name'=>$val['place_name'],
                'attr_list'=>$temp['attr_list'],
                'pinfo'=>$temp['qr_code_data']
            ];
        }

        $pagingData         = [
            'page' => $page,
            'pageSize' => $limit,
            'total' => $count,
            'keyword' => '',
        ];
        return $this->pagingData($listData, $pagingData);
    }

    private function getProductQrCodeData($info){
        $qrcodeId = $info['id'];
        $qrcodeSn = $info['sn'];
        $qrcodeStr          = '1-'.$qrcodeId.'-'.$qrcodeSn;

        $text           = $info['product_name'];
        $printData[]    = \App\Engine\KmPrinter::text($text,10,10,4);//材料名称
        $printData[]    = \App\Engine\KmPrinter::text($qrcodeSn,200,15,3);//二维码编号
        $text           = $info['place_name'];
        $printData[]    = \App\Engine\KmPrinter::text($text,440,15,3);//堆位
        $printData[]    = \App\Engine\KmPrinter::line(10,55,590,55);
        $where          = ['product_id'=>$info['product_id']];
        $fieldsList     = \App\Eloquent\Ygt\ProductFields::getList($where,'',6,'',['id','asc']);
        $i              = 1;

        $attr_list = [];

        foreach ($fieldsList as $key=>$val)
        {
            $n              = $key%2;
            $y              = 35 + $i * 40;
            if($n==1){
                $x          = 200;
                $i          += 1;
            }else{
                $x          = 10;
            }
            $fieldName      = $val['field_name'];
            $fieldType      = $val['field_type'];
            $fieldValue     = $fieldType==1 ? $val['varchar'] : $val['numerical'];
            $text           = $fieldName.':'.$fieldValue;

            $attr_list[] = $text;

            $printData[]    = \App\Engine\KmPrinter::text($text,$x,$y,5);
        }
        $printData[]        = \App\Engine\KmPrinter::qrcode($qrcodeStr,440,80);
        $result             = \App\Engine\KmPrinter::output($printData);

        return ['qr_code_data'=>$result,'attr_list'=>$attr_list];
    }


    public function getProductPurchaseWaterListOld(){
        $userId             = Func::getHeaderValueByName( 'userid',$this->userId );
        $userInfo           = DepartmentUser::getCurrentInfo( $userId );
        if(!$userInfo)
        {
            xThrow(ERR_PARAMETER,'登录失败');
        }
        $date          = request('date','');
        $id          = request('id');
        $page          = request('page',1);

        if (!$id)
        {
            xThrow(ERR_PARAMETER);
        }

        //取材料的流水
        $limit          = 10;
        $offset         = ($page - 1) * $limit;

        $StockWaterObj = new Stock();
        $StockWaterObj = $StockWaterObj->where('ygt_stock.product_id','=',$id)
            ->where('relate_type','=',3);

        if(!empty($date)){
            $startTime = strtotime($date);
            $endTime = $startTime+24*3600;

            $StockWaterObj = $StockWaterObj->whereBetween('ygt_stock.created_at',[$startTime,$endTime]);
        }

        //获得总数
        $count = $StockWaterObj->count();

        $info =[];
        //获得采购总量
        $info['number'] = $StockWaterObj->sum('number');
        //获得采购总金额
        $info['money'] = $StockWaterObj->sum('total_price');

        $lists = $StockWaterObj
            ->leftJoin('ygt_user','ygt_user.id','=','ygt_stock.operate_uid')
            ->leftJoin('ygt_purchase','ygt_purchase.id','=','ygt_stock.relate_id')
            ->skip($offset)->take($limit)
            ->orderBy('created_at','desc')
            ->get([
                'ygt_stock.id',
                //'ygt_stock.type',
                'ygt_stock.number',
                'ygt_stock.total_price',
                //'ygt_stock.last_product_number as residual_number',
                'ygt_purchase.purchase_number as sn',
                'ygt_stock.created_at',
                //'ygt_stock.relate_type',
                'ygt_user.truename as operate_name'
            ])->toArray();

        foreach($lists as $key=>$val){
            $lists[$key]['created_time'] = date('%Y-%m-%d %H:%M:%S',$lists[$key]['created_at']);
            $lists[$key]['price'] = sprintf("%.2f",$lists[$key]['total_price']/$lists[$key]['number']);
        }

        $listData           = [
            'info'=>$info,
            'list'=>$lists,
        ];
        $pagingData         = [
            'page' => $page,
            'pageSize' => $limit,
            'total' => $count,
            'keyword' => ''
        ];
        return $this->pagingData($listData, $pagingData);
    }


    public function getWaterWithInfo()
    {
        $userId             = Func::getHeaderValueByName( 'userid',$this->userId );
        $userInfo           = DepartmentUser::getCurrentInfo( $userId );


        $relateType = request('relate_type');
        $relateId = request('relate_id');

        if(!$userInfo)
        {
            xThrow(ERR_PARAMETER,'登录失败');
        }
        $productId          = request('product_id',0);
        //集合材料处理
        if(strstr($productId,'A')){
            //集合材料取集合材料下的第一个sku材料
            $tmpAssemblageMaterialId = str_replace('A','',$productId);
            $materialRow = \App\Eloquent\Ygt\AssemblageMaterial::withTrashed()->where(['id'=>$tmpAssemblageMaterialId])->first();
            $productId = $materialRow['id'];
        }


        $page               = request('page',1);
        if (!$productId)
        {
            xThrow(ERR_PARAMETER);
        }
        $companyId          = $userInfo->company_id;
        $where              = ['company_id'=>$companyId,'user_id'=>$userId];
        $departmentUser     = \App\Eloquent\Ygt\DepartmentUser::getInfo($where);
        $privilegeId        = $departmentUser->privilege_id;
        $isSale             = \App\Eloquent\Ygt\Privilege::getAppnodeId( $privilegeId, 10 );//是否采购员
        $printButton        = 1;
        if($isSale)
        {
            $printButton    = 0;
        }
        //取材料的详情
        $where              = ['ygt_product.id'=>$productId];
        $info               = Product::getJoinInfo($where,3);
        if(!$info)
        {
            xThrow(ERR_PRODUCT_NOT_EXIST);
        }
        $product            = $info->toArray();
        if(array_key_exists('seller_company_name',$product) && is_null($product['seller_company_name']))
        {
            $product['seller_company_name']   = '';
        }
        if(array_key_exists('customer_name',$product) && is_null($product['customer_name']))
        {
            $product['customer_name']           = '';
        }
        //取材料的图片
        $imgId              = $product['img_id'];
        $imgUrl             = Func::getImgUrlById($imgId);
        $product['img_url'] = $imgUrl;
        $productIdArr       = [$productId];

        //调整完集合材料后
        if(isset($product['assemblage_material_id'])){
            $tmpAssemblageMaterialId = $product['assemblage_material_id'];
        }else{
            $tmpAssemblageMaterialId = $product['id'];
        }
        $where = ['assemblage_material_id' => $tmpAssemblageMaterialId];
        $customFieldsData   = ProductFields::getTransformListToArr($where);


        $product            = Product::addCustomFieldsToInfo($product,$customFieldsData,2);
        //材料的累计入库和出库
        $where      = ['type'=>1,'product_id'=>$productId];
        $numberIn   = Stock::where($where)->sum('number');
        $where      = ['type'=>2,'product_id'=>$productId];
        $numberOut  = Stock::where($where)->sum('number');;
        $product['number_in']   = $numberIn;
        $product['number_out']  = -$numberOut;
        //取材料的流水
        $limit          = 10;
        $offset         = ($page - 1) * $limit;
        $where          = [
            'ygt_stock.product_id'=>$productId
        ];
        $stockList      = Stock::getJoinList($where,$limit,$offset);
        $stockList      = StockEngine::composeList($stockList);
        $where          = ['product_id'=>$productId];

        if($relateType && $relateId){
            $where['relate_type'] = $relateType;
            //$relateId需处理
            $relateId = \App\Eloquent\Ygt\OrderProcessCourse::where(['order_process_id'=>$relateId])->first()->id;
            $where['relate_id'] = $relateId;
        }

        $count          = Stock::getCount($where);

        $listData       = [
            'print_button'=>$printButton,
            'info'=>$product,
            'list'=>$stockList,
        ];
        $pagingData     = [
            'page' => $page,
            'pageSize' => $limit,
            'total' => $count,
            'keyword' => ''
        ];
        return $this->pagingData($listData, $pagingData);


    }

    /**
     * @return 入库信息
     */
    public function getStockList()
    {
        $params = request()->only('product_id', 'page');
        $params['page'] = request('page', 1);
        $rules = [
            'product_id' => 'required|integer',
        ];
        $this->validateRequestParameters($params, $rules);


        $stockModel = new Stock();

        $page = $params['page'];
        $limit = 10;
        $offset = ($page - 1) * $limit;
        $where = ['ygt_stock.product_id' => $params['product_id']];

        $stockList = StockEngine::getWaterList($where, $page, $limit);

        StockEngine::composeList($stockList);

        $count = $stockModel->getCount($where);

        $pagingData = [
            'page' => $page,
            'pageSize' => $limit,
            'total' => $count,
            'keyword' => ''
        ];
        return $this->pagingData($stockList, $pagingData);
//            xThrow(404002);
//            $this->response->error('This is an error.', 123456);

    }

    /**
     * @return string
     * 入库
     */
    public function stockIn()
    {
        $params = request()->only('product_id', 'product_name', 'product_no', 'barcode', 'number', 'category_id', 'unit_price', 'distribution_company', 'distribution_time', 'contact_number', 'img_id', 'unit', 'weight', 'remark', 'is_customer','customer_id', 'order_id', 'spec', 'is_print');
        $params['img_id'] = $params['img_id'] ? $params['img_id'] : 0;
        $params['remark'] = $params['remark'] ? $params['remark'] : '';
        $params['is_customer'] = $params['is_customer'] ? $params['is_customer'] : 0;
        $params['customer_id'] = $params['customer_id'] ? $params['customer_id'] : 0;
        $params['order_id'] = $params['order_id'] ? $params['order_id'] : 0;
        $params['unit'] = $params['unit'] ? $params['unit'] : '';
        $params['spec'] = $params['spec'] ? $params['spec'] : '';
        $params['weight'] = $params['weight'] ? $params['weight'] : 0;
        $params['distribution_time'] = request('distribution_time', date('Y-m-d H:i:s'));
        if($params['is_customer'] == 0)
        {
            $params['customer_id'] = 0;
        }

        $user_id = Func::getHeaderValueByName('userid');
        $info = DepartmentUser::getCurrentInfo($user_id);


        $params['unit_price'] = isset($params['unit_price']) ? $params['unit_price'] : 0;


        $rules = [
//            'distribution_company' => 'required',
//            'contact_number' => 'required',
//            'unit_price' => 'required|numeric',
        ];
        $this->validateRequestParameters($params, $rules);

        //非标属性在指定的范围内时才能通过
        //不管产品是否存在都需比较后才能入库
        $nonFieldsResult    = true;
        $nonFieldsResultArr = '';
        //非标属性提交过来的值
        $nonFieldsArr       = request('non_arr','');
        $nonFieldsList      = [];
        if($nonFieldsArr)
        {
            $nonFieldsList      = json_decode(htmlspecialchars_decode($nonFieldsArr), true);
        }
        $categoryId             = $params['category_id'];
        $cateNonstandardArr     = CategoryFields::getFieldListByType($categoryId,2);
        if($nonFieldsList){
            foreach($cateNonstandardArr as $key=>$val)
            {
                $valFieldName       = $val['field_name'];
                $valFieldValue      = $val['field_value'];
                $valMinValue        = $val['min_value'];
                $valMaxValue        = $val['max_value'];
//                $minValue           = $valFieldValue - $valMinValue;
//                $maxValue           = $valFieldValue + $valMaxValue;
                foreach($nonFieldsList as $k=>$v)
                {
                    if($valFieldName == $v['field_name'])
                    {
                        $vFieldValue        = $v['field_value'];
                        $vFieldValue        = intval($vFieldValue);
                        if($vFieldValue < $valMinValue || $vFieldValue > $valMaxValue)
                        {
                            $nonFieldsResult        = false;
                            $nonFieldsResultArr[]   = $valFieldName.'不'.$vFieldValue.'在范围内';
                        }
                    }
                }
            }
        }
        if($nonFieldsResult === false)
        {
            $nonFieldsResultMessage     = implode(',',$nonFieldsResultArr);
            xThrow(ERR_PARAMETER, $nonFieldsResultMessage);
        }

        //开始查产品，如果有传入产品ID，查询已有产品，如果没有则创建产品
        $productModel = new Product();
        if ($productId = $params['product_id']) {
            $rules = [
                'product_id' => 'required|integer',
                'number' => 'required|integer'
            ];
            $this->validateRequestParameters($params, $rules);
            $productInfo = $productModel->getProductInfoById($productId);
            if (!$productInfo->toArray()) {
                xThrow(ERR_PRODUCT_NOT_EXIST);
            }
        } else {
            $rules = [
                'product_name' => 'required',
//                'product_no' => 'required',
                'category_id' => 'required|integer',
                'number' => 'required|integer',
            ];
            $this->validateRequestParameters($params, $rules);

            $params['product_no'] = $params['product_no'] ? $params['product_no'] : EngineProduct::createProductNo();

            $productInfo = $productModel->getProductInfoByNo($params['product_no']);
            if (!$productInfo or !$productInfo->toArray()) {
                $productData = [
                    'product_name' => $params['product_name'],
                    'product_no' => $params['product_no'],
                    'unit' => $params['unit'],
                    'weight' => $params['weight'],
                    'category_id' => $params['category_id'],
                    'company_id' => $info->company_id,
                    'img_id' => $params['img_id'],
                    'spec' => $params['spec'],
                    'is_customer' => $params['is_customer'],
                    'customer_id' => $params['customer_id'],
                ];


                if (!$productInfo = $productModel->addProduct($productData)) {
                    xThrow(ERR_PRODUCT_CREATE_FAIL);
                }

                //自定义字段
                $fields = request('custom_fields','');
                if($fields!='')
                {
                    $fields = json_decode(htmlspecialchars_decode($fields), true);
                    $ProductFieldsModel = new ProductFields();
                    foreach ($fields as $v) {
                        $comumnName = EngineProduct::getFieldColumn($v['field_type']);
                        $comumnNameValue = $v['field_value'];
                        if($comumnName=='numerical')
                        {
                            $comumnNameValue    = intval($comumnNameValue);
                        }
                        $fieldData = [
                            'product_id' => $productInfo->id,
                            'field_name' => $v['field_name'],
                            'field_type' => $v['field_type'],
                            $comumnName => $comumnNameValue
                        ];
                        $ProductFieldsModel->insertData($fieldData);
                    }
                }

            } else {
                xThrow(ERR_PRODUCT_NO_IS_EXIST);
            }
        }
        //到此拿到 $productInfo

        //开始入库
        $stockModel = new Stock();
        $water_no = StockEngine::createWaterNo();
//        $stockData = ['number' => $params['number'], 'product_id' => $productInfo->id, 'stock_type'=>1, 'remark' => $params['remark'], 'water_no' => $water_no];


        $stockInData = [
            'unit_price' => $params['unit_price'] ? $params['unit_price'] : 0,
            'distribution_company' => $params['distribution_company'],
            'distribution_time' => strtotime($params['distribution_time']),
            'contact_number' => $params['contact_number'],
            'uid' => $user_id,
        ];

        $stockInModel = new StockIn();
        $stockInId = $stockInModel->addStock($stockInData);

        //每次入库的非标属性是可以不一样的
        if($stockInId && $nonFieldsList && $cateNonstandardArr)
        {
            foreach($cateNonstandardArr as $key=>$val)
            {
                $valFieldName       = $val['field_name'];
                $valFieldValue      = $val['field_value'];
                foreach($nonFieldsList as $k=>$v)
                {
                    if($valFieldName == $v['field_name'])
                    {
                        $vFieldValue        = $v['field_value'];
                        $vFieldValue        = strval($vFieldValue);
                        $stockFieldData     = [
                            'table_name'=>'stockin',
                            'table_id' => $stockInId,
                            'field_id' => $val['id'],
                            'field_name' => $v['field_name'],
                            'field_value' => $vFieldValue,
                        ];
                        StockFields::insertOneData($stockFieldData);
                    }
                }
            }
        }

        $supplierId = request('supplier_id', 0);
        $stockData[] = [
            'number' => $params['number'],
            'total_price' => $params['number'] * $params['unit_price'],
            'product_id' => $productInfo->id,
            'company_id' => $info->company_id,
            'operate_uid' => $user_id,
            'water_no' => $water_no,
            'relate_type' => 3,
            'relate_id' => $stockInId,
            'supplier_id' => $supplierId,
        ];
        $stockResult = StockEngine::addStockData($stockData);

        $returnData = [
            'msg' => 'ok',
            'product_id' => $productInfo->id
        ];
        if ($params['is_print'] == 1) {
            $printResult = StockEngine::stockInPrint(['water_no' => $water_no]);
            $returnData['pinfo'] = $printResult;

        }

        $privileges = Privilege::getPrivilegeIds($info->company_id, 7);
        foreach ($privileges as $v) {
            $messageContent = '材料名称：' . $productInfo->product_name . ' rnrn 入库数量：' . $params['number'];
            $data = [
                'company_id' => $info->company_id, 'privilege_id' => $v,
                'form_user_id' => $user_id, 'to_user_id' => '',
                'foreign_key' => $stockInId,
                'type' => 4, 'type_id' => $stockInId,
                'title' => '有新材料采购入库', 'content' => $messageContent
            ];
            //UserMessage::sendProductOrderMessage($data);
        }


        /*$printStr = '';
        $printStr .= Printer::strong($productInfo->product_name,'center');
        $printStr .= Printer::br();
        $printStr .= Printer::normal($productInfo->product_no,'center');
        $printStr .= Printer::br();
        $printStr .= Printer::br();

        $printStr .= Printer::keyValue(['数量'=>$params['number'],'规格'=>$productInfo->spec]);

        $printStr .= Printer::br();
        $printStr .= Printer::br();
        $printStr .= Printer::qrcode($productInfo->product_no);
        $printStr .= Printer::br();
        $printStr .= Printer::normal($water_no,'center');


        Printer::p($printStr);*/

        return $returnData;

    }


    /**
     * @return string
     * 入库
     */
    public function purchaseMaterialAdd()
    {
        $params = request()->only('product_id', 'product_name', 'product_no', 'barcode', 'number', 'category_id', 'unit_price', 'distribution_company', 'distribution_time', 'contact_number', 'img_id', 'unit', 'weight', 'remark', 'customer_id', 'order_id', 'spec', 'is_print');
        $params['img_id'] = $params['img_id'] ? $params['img_id'] : 0;
        $params['remark'] = $params['remark'] ? $params['remark'] : '';
        $params['customer_id'] = $params['customer_id'] ? $params['customer_id'] : 1;
        $params['order_id'] = $params['order_id'] ? $params['order_id'] : 0;
        $params['unit'] = $params['unit'] ? $params['unit'] : '';
        $params['spec'] = $params['spec'] ? $params['spec'] : '';
        $params['weight'] = $params['weight'] ? $params['weight'] : 0;

        $user_id = Func::getHeaderValueByName('userid');
        $info = DepartmentUser::getCurrentInfo($user_id);


        $params['unit_price'] = isset($params['unit_price']) ? $params['unit_price'] : 0;

        $rules = [
//            'distribution_company' => 'required',
//            'contact_number' => 'required',
//            'unit_price' => 'required|numeric',
        ];
        $this->validateRequestParameters($params, $rules);

        //开始查产品，如果有传入产品ID，查询已有产品，如果没有则创建产品
        $productModel = new Product();
        if ($productId = $params['product_id']) {
            $rules = [
                'product_id' => 'required|integer',
                'number' => 'required|integer'
            ];
            $this->validateRequestParameters($params, $rules);
            $productInfo = $productModel->getProductInfoById($productId);
            if (!$productInfo->toArray()) {
                xThrow(ERR_PRODUCT_NOT_EXIST);
            }
        } else {
            $rules = [
                'product_name' => 'required',
//                'product_no' => 'required',
                'category_id' => 'required|integer',
                'number' => 'required|integer',
            ];
            $this->validateRequestParameters($params, $rules);

            $params['product_no'] = $params['product_no'] ? $params['product_no'] : EngineProduct::createProductNo();

            $productInfo = $productModel->getProductInfoByNo($params['product_no']);
            if (!$productInfo or !$productInfo->toArray()) {
                $productData = [
                    'product_name' => $params['product_name'],
                    'product_no' => $params['product_no'],
                    'unit' => $params['unit'],
                    'weight' => $params['weight'],
                    'category_id' => $params['category_id'],
                    'company_id' => $info->company_id,
                    'img_id' => $params['img_id'],
                    'spec' => $params['spec'],
                ];


                if (!$productInfo = $productModel->addProduct($productData)) {
                    xThrow(ERR_PRODUCT_CREATE_FAIL);
                }

                //自定义字段
                $fields = request('custom_fields','');
                if($fields!='')
                {
                    $fields = json_decode(htmlspecialchars_decode($fields), true);
                    $ProductFieldsModel = new ProductFields();
                    foreach ($fields as $v) {
                        $comumnName = EngineProduct::getFieldColumn($v['field_type']);
                        $comumnNameValue = $v['field_value'];
                        if($comumnName=='numerical')
                        {
                            $comumnNameValue    = intval($comumnNameValue);
                        }
                        $fieldData = [
                            'product_id' => $productInfo->id,
                            'field_name' => $v['field_name'],
                            'field_type' => $v['field_type'],
                            $comumnName => $comumnNameValue
                        ];
                        $ProductFieldsModel->insertData($fieldData);
                    }
                }

            } else {
                xThrow(ERR_PRODUCT_NO_IS_EXIST);
            }
        }
        //到此拿到 $productInfo



        $returnData = [
            'product_id' => $productInfo->id,
            'product_num' => $params['number'],
            'product_img' => Func::getImgUrlById($params['img_id']),//材料图片
            'product_fileds' => $fields,//自定义属性
        ];

        return $returnData;

    }


    public function stockOut()
    {
        $params = request()->only('product_id', 'unit_price', 'distribution_company', 'contact_number');

    }

    /**
     * 库存详情 ape接口
     */
    public function productStockInfo()
    {
        $productId = request('product_id');
        $productModel = new Product();
        $productInfoResult = $productModel->getProductInfoById($productId);
        if ($productInfoResult and $productInfo = $productInfoResult->toArray()) {
            $stockList = $this->getStockList();
            $stockModel = new Stock();
            $where = ['ygt_stock.product_id' => $productId];
            $stockList = $stockModel->getStockList($where, 'ygt_stock.id,ygt_stock.water_no,ygt_stock.product_id,ygt_stock.number,ygt_stock.type');
            $tableViewSource = [];
            foreach ($stockList as $k => $v) {
                $tableViewSource[] = [
                    'idName' => 21,
                    '$companyValue' => $v['distribution_company'],
                    '$orderNumber' => $v['water_no'],
                    '$functionNameValue' => 'clear' . $v['id'],
                    '$list' => [
                        [
                            '$leftValue' => '价格',
                            '$rightValue' => $v['unit_price']
                        ],
                        [
                            '$leftValue' => '可用库存',
                            '$rightValue' => $v['number']
                        ],
                        [
                            '$leftValue' => '实际库存',
                            '$rightValue' => $v['number']
                        ],
                        [
                            '$leftValue' => '操作员',
                            '$rightValue' => $v['operator']
                        ]
                    ]
                ];
            }
            $where                  = ['product_id'=>$productId];
            $fields                 = 'field_name,field_type,varchar,numerical';
            $productFields          = ProductFields::getList($where,$fields,2)->toArray();
            $specificationName      = $weightName = $specificationValue = $weightValue ='';
            $specificationNameW     = $weightNameW = 100;
            if(!empty($productFields))
            {
                foreach($productFields as $key=>$val)
                {
                    if($val['field_type']==1){
                        $fieldValue     = $val['varchar'];
                    }else{
                        $fieldValue     = $val['numerical'];
                    }
                    $productFields[$key]['field_value'] = $fieldValue;
                }
                if(isset($productFields[0]))
                {
                    $specificationName  = $productFields[0]['field_name'];
                    $specificationValue = $productFields[0]['field_value'];
                    $specificationSize  = mb_strlen($specificationName);
                    $specificationNameW = $specificationSize * 20;
                }
                if(isset($productFields[1]))
                {
                    $weightName         = $productFields[1]['field_name'];
                    $weightValue        = $productFields[1]['field_value'];
                    $weightNameSize     = mb_strlen($weightName);
                    $weightNameW        = $weightNameSize * 20;
                }
            }
            $returnOrderTypeList = [
                'pageID' => 7,
                'data' => [
                    '$productImage' => Func::getImgUrlById($productInfo['img_id']),
                    '$productNameValue' => $productInfo['product_name'],
                    '$numberValue' => $productInfo['product_no'],
                    '$averagePriceValue' => $productInfo['price'],
                    '$specificationName' => $specificationName,
                    '$specificationValue' => $specificationValue,
                    '$specificationNameW' => $specificationNameW,
                    '$weightName' => $weightName,
                    '$weightValue' => $weightValue,
                    '$weightNameW' => $weightNameW,
                    '$sweepFunctionValue' => "sweepAction",
                    '$manualFunctionValue' => "manualpAction",
                    '$repertoryValue' => $productInfo['number'],
                    '$imageClickFunctionName' => "imageClickAction",
                    '$tableViewSource' => $tableViewSource
                ]
            ];

            return $returnOrderTypeList;
        } else {
            xThrow(405001);
        }
    }

    public function delStock()
    {
        $id = request('id');
        $stockModel = new Stock();
        $stockModel->del(['id' => $id]);
        return "OK";
    }


    //采购录入的信息详情
    public function purchaseInfo()
    {
        $id = request('id');
        $info = StockIn::where('id', $id)->select([
            'id',
            'unit_price',
            'distribution_company',
            'distribution_time',
            'contact_number',
        ])->first();

        $relateType = StockEngine::getRelateType(3);
        $where = ['relate_type' => 3, 'relate_id' => $id];


        $stockInfo = Stock::getOneData($where);

        $productInfo = Product::where('id', $stockInfo->product_id)->first();

        $productInfo->custom_fields = $productInfo->fields->map(function ($item) {
            $comumnName = EngineProduct::getFieldColumn($item->field_type);

            $re = [
                'field_name' => $item->field_name,
//                    'field_type'=> $item->field_type,
                'field_value' => $item->$comumnName
            ];
            return $re;
        });

        $info->number = $stockInfo->number;
        $info->custom_fields = $productInfo->custom_fields;
        $info->img_url = url('api/service/stock/qrcode?water_no=' . $stockInfo->water_no);

        $info->distribution_time = date('Y-m-d H:i:s', $info->distribution_time);


        return $info;

    }

    public function qrcode()
    {
        $waterNo = request('water_no');

        $where = ['water_no' => $waterNo];
        $stockInInfo = Stock::getOneData($where);
        $result = Func::qrcode('w:' . $waterNo . ',' . 'm:' . $stockInInfo->product_no);
        echo $result;
        die;
    }


    public function printer()
    {
        $id = request('id');
        if ($id) {
            $where = ['id' => $id];
        } else {
            xThrow(ERR_STOCK_INFO_NOT_EXIST);
        }

        $printResult = StockEngine::stockInPrint($where);
        return $printResult;
    }


    //采购员填写材料价格
    public function purchasePriceSubmit()
    {
        $materialId = request('material_id');
        $price = request('price');
        if(!$materialId){
            return [
                'code' => 1,
                'message' => '参数错误',
            ];
        }


        if(!$price){
            return [
                'code' => 1,
                'message' => '请填写价格',
            ];
        }

        $tmpObj = \App\Eloquent\Ygt\Product::where(['id'=>$materialId])->first();
        $tmpObj->price = $price;
        $tmpObj->save();

        return '操作成功';
    }
}